from flask import Blueprint, render_template, request, session
from flask_jwt_extended import jwt_required
from flask_login import login_required

from applications.common.curd import model_to_dicts
from applications.common.helper import ModelFilter
from applications.common.utils.http import table_api, wxuser_success_api, address_api
from applications.common.utils.validate import xss_escape
from applications.exts import db
from applications.exts.cache import cache
from applications.models import Wx_User_Address
from applications.models.wx_user import WxUser
from applications.schemas import WxUserOutSchema, WxUserAddressOutSchema

wxuser_user_address = Blueprint('wxuser_address', __name__, url_prefix='/wxuser/user/address')


# 用户地址管理
@wxuser_user_address.route('/')
@login_required
# flask 实现 Authorization请求报头认证
# @authorize("wxuser:role:main", log=True)
def main():
    return render_template('wxuser/address/main.html')


# 用户地址分页查询
@wxuser_user_address.route('/data')
@login_required
# @authorize("admin:user:main", log=True)
def data():
    # 获取请求参数
    openid = xss_escape(request.args.get('openid', type=str))
    username = xss_escape(request.args.get('username', type=str))
    # 查询参数构造
    mf = ModelFilter()
    if openid:
        mf.contains(field_name="openid", value=openid)
    if username:
        mf.contains(field_name="username", value=username)
    # if dept_id:
    #     mf.exact(field_name="dept_id", value=dept_id)
    # orm查询

    # 使用分页获取data需要.items
    wxuser = Wx_User_Address.query.filter(mf.get_filter(model=Wx_User_Address)).layui_paginate()
    count = wxuser.total
    # 返回api
    return table_api(data=model_to_dicts(schema=WxUserAddressOutSchema, data=wxuser.items), count=count)


# ==============wx===============


# wx用户地址管理
@wxuser_user_address.route('/wxuseradd', methods=["POST"])
@jwt_required()
def wxuseradd():
    req_json = request.json

    print(req_json)

    avatar = xss_escape(req_json.get("avatar"))
    token = xss_escape(req_json.get("token"))
    openid = xss_escape(req_json.get("openid"))
    addresslist = req_json.get('addresslist')

    username = xss_escape(addresslist.get('username'))
    phone = xss_escape(addresslist.get('phone'))
    address = xss_escape(addresslist.get('address'))
    print('req_json:', username, phone, address)

    print('openid:', cache.get('openid'))

    wxuseraddress = Wx_User_Address()
    wxuseraddress.phone = phone
    wxuseraddress.username = username
    wxuseraddress.avatar = avatar
    wxuseraddress.openid = openid
    wxuseraddress.address = address

    db.session.add(wxuseraddress)
    db.session.commit()

    return wxuser_success_api(errno=0, msg='地址添加添加成功')


# wx查询收货地址

@wxuser_user_address.route('/wxuserlist', methods=["POST"])
@jwt_required()
def wxuserlist():
    req_json=request.json
    openid=req_json.get('openid')
    print(openid)
    wx_user_list = Wx_User_Address.query.filter(Wx_User_Address.openid==openid).all()
    wx_useraddress_list=[]
    for user_address in wx_user_list:
        wx_useraddress_list.append(user_address.to_dict())
        # print(i.to_dict())
    # WxUserAddressOutSchema
    return address_api(errno=0, data=wx_useraddress_list, msg='地址查询成功')

    # return address_api(errno=0, data=model_to_dicts(schema=WxUserAddressOutSchema, data=wx_user_list), msg='授权登录成功')



# wx修改收货地址

@wxuser_user_address.route('/wxuserupdate', methods=["PUT"])
@jwt_required()
def wxuserupdate():
    req_json = request.json
    id=req_json.get('id')
    useraddress=req_json.get('useraddress')
    username=xss_escape(useraddress.get('username'))

    phone = xss_escape(useraddress.get('phone'))
    address = xss_escape(useraddress.get('address'))
    print(req_json)

    wx_user_list = Wx_User_Address.query.get(id)
    if wx_user_list:
        if username !='':
            wx_user_list.username=username
        if phone !='':
            wx_user_list.phone=phone
        if address !='':
            wx_user_list.address=address
        db.session.commit()
    # WxUserAddressOutSchema
    return address_api(errno=0, msg='修改成功')

# 删除收货地址
@wxuser_user_address.route('/wxuserdelete', methods=["DELETE"])
@jwt_required()
def wxuserdelete():
    req_json=request.json
    id = req_json.get('id')
    print(req_json)

    res=Wx_User_Address.query.filter(Wx_User_Address.id==id).delete()
    db.session.commit()
    print(res)
    if res>0:
        return address_api(errno=0, msg='删除成功')
    else:
        return address_api(errno=1, msg='删除失败')

